<template>
  <div>
    <el-dialog
      :title="info.type == 'add' ? '新增菜单' : '编辑菜单'"
      :visible.sync="info.isShow"
      width="60%"
    >
      <span>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="first">
              <el-form-item label="一级分类" prop="first_cateid">
                <el-select
                  v-model="ruleForm.first_cateid"
                  placeholder="请选择"
                  @change="firstChange"
                >
                  <el-option
                    v-for="item in firstList"
                    :key="item.id"
                    :label="item.catename"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="二级分类" prop="second_cateid">
                <el-select
                  v-model="ruleForm.second_cateid"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in secondList"
                    :key="item.id"
                    :label="item.catename"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="商品名称" prop="goodsname">
                <el-input v-model="ruleForm.goodsname"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="price">
                <el-input v-model="ruleForm.price"></el-input>
              </el-form-item>
              <el-form-item label="市场价格" prop="market_price">
                <el-input v-model="ruleForm.market_price"></el-input>
              </el-form-item>
              <el-form-item label="商品图片" prop="img">
                <!-- action 上传的地址 -->
                <!-- auto-upload 是否自动上传 -->
                <!-- list-type 组件的形式，照片墙 -->
                <!-- on-preview 预览图片时，执行的函数 -->
                <!-- on-remove 移除时，处理的函数 -->
                <!-- on-change 文件修改时执行的函数 -->
                <!-- file-list 历史文件列表 -->
                <el-upload
                  action="#"
                  :auto-upload="false"
                  list-type="picture-card"
                  :on-remove="handleRemove"
                  :on-change="handleChange"
                  :file-list="fileList"
                  :limit="1"
                  :on-exceed="limtimg"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="商品规格" prop="specsid">
                <el-select
                  v-model="ruleForm.specsid"
                  placeholder="请选择"
                  @change="sepcsChange"
                >
                  <el-option
                    v-for="item in spacelist"
                    :key="item.id"
                    :label="item.specsname"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="规格属性值" prop="specsattr">
                <el-select
                  v-model="ruleForm.specsattr"
                  multiple
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in attrs"
                    :key="item.value"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="是否新品" prop="isnew">
                <el-radio-group v-model="ruleForm.isnew">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="2">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否热卖" prop="ishot">
                <el-radio-group v-model="ruleForm.ishot">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="2">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="ruleForm.status">
                  <el-radio :label="1">正常</el-radio>
                  <el-radio :label="2">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="详细描述" name="second">
              <div id="div1"></div>
              <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')"
                  >立即创建</el-button
                >
                <el-button @click="resetForm('ruleForm')">重置</el-button>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  categoryList,
  categoryInfo,
  spaceList,
  specsInfo,
  goodsAdd,
  goodsEdit,
} from "@/api.js";
//富文本编辑器
import E from "wangeditor";
export default {
  props: ["info"],
  data() {
    return {
      activeName: "first",
      //历史图片列表
      fileList: [],
      //一级分类下拉菜单
      firstList: [],
      //二级分类
      secondList: [],
      //商品规格
      spacelist: [],
      //商品属性
      attrs: [],
      ruleForm: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        img: "",
        description: "",
        specsid: 5,
        specsattr: "",
        market_price: "",
        isnew: 1,
        ishot: 1,
        status: 1, //1正常2禁用
      },
      options: [],
      rules: {
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
        ],
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "change" },
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "change" },
        ],
        specsid: [
          { required: true, message: "请选择商品规格", trigger: "change" },
        ],
        specsattr: [
          { required: true, message: "请选择属性值", trigger: "change" },
        ],
      },
    };
  },
  async created() {
    //获取一级分类下拉数据
    let res1 = await categoryList();
    this.firstList = res1.list;
    //商品规格
    let res2 = await spaceList({ page: 1, size: 999 });
    this.spacelist = res2.list;
    // console.log(object);
  },
  methods: {
    //一级分类改变需要获取对应的二级数据，每次都要获取
    async firstChange() {
      let res = await categoryInfo(this.ruleForm.first_cateid);
      this.secondList = res.list;
    },
    //商品规格改变了，属性也要改变
    async sepcsChange() {
      if (this.ruleForm.specsid) {
        let res = await specsInfo(this.ruleForm.specsid);
        this.attrs = res.list[0].attrs;
      }
    },
    //删除图片
    handleRemove() {
      this.ruleForm.img = "";
    },
    //修改文件
    handleChange(file) {
      this.ruleForm.img = file.raw;
    },
    limtimg() {
      this.$message({
        message: "只能上传一个图",
        type: "warning",
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //写入编辑器内容
          this.ruleForm.description = this.editor.txt.html();
          //属性转为字符串
          this.ruleForm.specsattr = this.ruleForm.specsattr.join(",");
          let fd = new FormData();
          if (this.ruleForm.firstcatename || this.ruleForm.secondcatename) {
            delete this.ruleForm.firstcatename;
            delete this.ruleForm.secondcatename;
          }

          for (const key in this.ruleForm) {
            fd.append(key, this.ruleForm[key]);
          }
          if (this.info.type === "add") {
            let res = await goodsAdd(fd);
          } else {
            let res = await goodsEdit(fd);
          }
          this.info.isShow = false;
          this.$emit("update");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //给表单复制
    setValue(info) {
      this.ruleForm = { ...info };
      //等待dom加载完成
      this.$nextTick(() => {
        if (!this.editor) {
          //打开弹窗初始化编辑器
          this.editor = new E("#div1");
          this.editor.create();
        }
        //编辑时将原始数据写进去
        this.editor.txt.html(this.ruleForm.description);
        this.fileList=[]
        if (this.ruleForm.img) {
          this.fileList.push({
            name: "u-admin",
            url: this.$host + this.ruleForm.img,
          });
        }
      });
      console.log(this.ruleForm);
      if (this.info.type == "edit") {
        this.ruleForm.specsattr = this.ruleForm.specsattr.split(",");
        this.firstChange();
        this.sepcsChange();
      }
    },
  },
};
</script>
<style scoped>
#div1 {
  margin-bottom: 10px;
}
</style>